<?php

declare(strict_types=1);

namespace app\admin\command;

use app\common\model\BasketballCompetitions;
use app\common\model\BasketballComptitions;
use app\common\model\FootballCompetitions;
use app\common\model\MatchesSeason;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class Season extends Command
{
    //赛事年份  已经拉去完了  不用执行了
    protected $model;
    protected function configure()
    {
        // 指令配置
        $this->setName('season')
            ->addArgument('action', Argument::OPTIONAL, '参数')
            ->setDescription('赛事年份');
    }

    protected function execute(Input $input, Output $output)
    {
        $action = trim($input->getArgument('action'));
        if ($action == 'football') {
            $this->model = new FootballCompetitions();
        } else {
            $this->model = new BasketballCompetitions();
        }
        $res =  $this->model->field('id,api_id,name')->select();
        foreach ($res as $key => $v) {
            $output->writeln('=========================循环第' . ($key + 1) . '个数据，开始循环赛事名称为:' . $v['name'] . '=====================================');
            $url = 'https://api-f.kqiu.cn/api/v1/' . $action . '/competition/season-list?competition_id=' . $v['api_id'];
            $res = curl_get($url);
            $arr = json_decode($res, true);
            if ($arr['code'] == 0) {
                foreach ($arr['data'] as $c_key => $c_v) {
                    $result_arr = [
                        'foreign_key_id' => $v['id'],
                        'competition_id' => $v['api_id'],
                        'season_id' => $c_v['season_id'],
                        'year' => $c_v['year'],
                        'is_current' => $c_v['is_current'],
                        'type' => $action
                    ];
                    $is_find = MatchesSeason::where(['foreign_key_id' => $v['id'],'competition_id'=>$v['api_id'],'year'=> $c_v['year'],'type' => $action])->find();
                    
                    if (empty($is_find)) {
                        MatchesSeason::create($result_arr);
                        $str = "add";
                    } else {
                        $is_find->save($result_arr);
                        $str = 'update';
                    }
                    $output->writeln('=========================循环第' . ($key + 1) . '个数据，' . $v['name'].',' .$str. '完成=====================================');
                }
            }else{
                $output->writeln('api参数出错');
            }
        }
        // 指令输出
        $output->writeln('season');
    }
}
